package org.jeecgframework.web.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mybatis.ext.WiseCoreService;

import org.apache.log4j.Logger;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.service.CbsEquipmentErrorLogServiceI;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;

import java.io.IOException;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 备件申请异常表
 * @date 2018-05-21 10:08:17
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsEquipmentErrorLogController")
public class CbsEquipmentErrorLogController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsEquipmentErrorLogController.class);

    @Autowired
    private CbsEquipmentErrorLogServiceI cbsEquipmentErrorLogService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private WiseCoreService wiseCoreService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 备件申请异常表列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsEquipmentErrorLog")
    public ModelAndView cbsEquipmentErrorLog(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_equipment_error_log/cbsEquipmentErrorLogList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsEquipmentErrorLogEntity cbsEquipmentErrorLog, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        try {
            Map param = new HashMap<>();
            boolean flag = false; //页面查询条件为空时不做查询
    		Map<String, String[]> parameterMap = request.getParameterMap();
            for (String key : parameterMap.keySet()) {
                if (key.equals("code") || key.equals("isClose") || key.equals("needSystemRevise") ||
                		key.equals("sn") || key.equals("createDate_begin") || key.equals("createDate_end")) {
                    if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                        flag = true;//页面 查询条件为空不做查询
                        break;
                    }
                }
            }
            if (flag) {
	            for (Object key : request.getParameterMap().keySet()) {
	                if ((String[]) request.getParameterMap().get(key) != null) {
	                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
	                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
	                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
	                        }
	                    }
	                }
	            }
	
	            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_begin")))) {
	                param.put("createDate_begin", oConvertUtils.getString(param.get("createDate_begin")) + " 00:00:00");
	            }
	            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_end")))) {
	                param.put("createDate_end", oConvertUtils.getString(param.get("createDate_end")) + " 23:59:59");
	            }
            } else {
            	param.put("isClose", 1);
            }
            wiseCoreService.selectDataGrid("getEquipmentErrorLogList", param, dataGrid);

        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 备件申请异常表新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsEquipmentErrorLogEntity cbsEquipmentErrorLog, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsEquipmentErrorLog.getId())) {
            cbsEquipmentErrorLog = cbsEquipmentErrorLogService.getEntity(CbsEquipmentErrorLogEntity.class, cbsEquipmentErrorLog.getId());
            req.setAttribute("cbsEquipmentErrorLogPage", cbsEquipmentErrorLog);
        }
        return new ModelAndView("com/zybk/cbs_equipment_error_log/cbsEquipmentErrorLog-add");
    }


    /**
     * 添加备件申请异常表
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsEquipmentErrorLogEntity cbsEquipmentErrorLog, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "备件申请异常表添加成功";
        try {
            cbsEquipmentErrorLogService.save(cbsEquipmentErrorLog);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "备件申请异常表添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 备件申请异常表编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsEquipmentErrorLogEntity cbsEquipmentErrorLog, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsEquipmentErrorLog.getId())) {
            cbsEquipmentErrorLog = cbsEquipmentErrorLogService.getEntity(CbsEquipmentErrorLogEntity.class, cbsEquipmentErrorLog.getId());
            req.setAttribute("cbsEquipmentErrorLogPage", cbsEquipmentErrorLog);
        }

        boolean flag = false;
        TSUser user = ResourceUtil.getSessionUserName();
        List<Map<String, Object>> roleList = systemService.findForJdbc("SELECT * FROM t_s_role r LEFT JOIN t_s_role_user u ON r.id = u.roleid where u.userid = '" + user.getId() + "';");
        if (StringUtil.isNotEmpty(roleList)) {
            if (roleList.size() > 0) {
                String num = (String) roleList.get(0).get("rolecode");
                if (num.equals(StaticValue.ROLE_CODE_ADMIN)) {
                    flag = true;
                }
            }
        }

        if (flag) {
            return new ModelAndView("com/zybk/cbs_equipment_error_log/cbsEquipmentErrorLog-adminUpdate");
        } else {
            return new ModelAndView("com/zybk/cbs_equipment_error_log/cbsEquipmentErrorLog-update");
        }

    }

    /**
     * 更新备件申请异常表
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsEquipmentErrorLogEntity cbsEquipmentErrorLog, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Date date=new Date();
        String description=request.getParameter("description");
        String abnormalResult=request.getParameter("abnormalResult");
        //获取登录用户
        TSUser user = ResourceUtil.getSessionUserName();
        message = "备件申请异常更新成功";
        CbsEquipmentErrorLogEntity t = cbsEquipmentErrorLogService.get(CbsEquipmentErrorLogEntity.class, cbsEquipmentErrorLog.getId());
        try {
            boolean flag = false;
            List<Map<String, Object>> roleList = systemService.findForJdbc("SELECT * FROM t_s_role r LEFT JOIN t_s_role_user u ON r.id = u.roleid where u.userid = '" + user.getId() + "';");
            if (StringUtil.isNotEmpty(roleList)) {
                if (roleList.size() > 0) {
                    String num = (String) roleList.get(0).get("rolecode");
                    if (num.equals(StaticValue.ROLE_CODE_ADMIN)) {
                        flag = true;
                    }
                }
            }

            if (flag) {
                t.setAdminAbnormalResult(cbsEquipmentErrorLog.getAdminAbnormalResult());
                t.setAdminDescription(cbsEquipmentErrorLog.getAdminDescription());
                t.setAdminUpdateDate(new Date());
                t.setAdminUpdateBy(user.getRealName());
                t.setNeedSystemRevise(cbsEquipmentErrorLog.getNeedSystemRevise());
            }else{
                t.setDescription(description);
                t.setAbnormalResult(abnormalResult);
                t.setHandleDate(date);
                t.setHandleUser(user.getUserName());
                t.setNeedSystemRevise(cbsEquipmentErrorLog.getNeedSystemRevise());
            }
            t.setIsClose(2);
            cbsEquipmentErrorLogService.saveOrUpdate(t);
            if (flag) {
                systemService.updateBySqlString("update cbs_equipment_error_log set update_name='"+""+"',update_date=null where id = '"+cbsEquipmentErrorLog.getId()+"'");
            }
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "备件申请异常处理失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 删除备件申请异常表
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsEquipmentErrorLogEntity cbsEquipmentErrorLog, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsEquipmentErrorLog = systemService.getEntity(CbsEquipmentErrorLogEntity.class, cbsEquipmentErrorLog.getId());
        message = "备件申请异常表删除成功";
        try {
            cbsEquipmentErrorLogService.delete(cbsEquipmentErrorLog);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "备件申请异常表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除备件申请异常表
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "备件申请异常表删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsEquipmentErrorLogEntity cbsEquipmentErrorLog = systemService.getEntity(CbsEquipmentErrorLogEntity.class,
                        id
                );
                cbsEquipmentErrorLogService.delete(cbsEquipmentErrorLog);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "备件申请异常表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbs_equipment_error_log/cbsEquipmentErrorLogUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CbsEquipmentErrorLogEntity cbsEquipmentErrorLog, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(CbsEquipmentErrorLogEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsEquipmentErrorLog, request.getParameterMap());
        List<CbsEquipmentErrorLogEntity> cbsEquipmentErrorLogs = this.cbsEquipmentErrorLogService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "备件申请异常表");
        modelMap.put(NormalExcelConstants.CLASS, CbsEquipmentErrorLogEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("备件申请异常表列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, cbsEquipmentErrorLogs);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsEquipmentErrorLogEntity cbsEquipmentErrorLog, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "备件申请异常表");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, CbsEquipmentErrorLogEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsEquipmentErrorLogEntity> listCbsEquipmentErrorLogEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsEquipmentErrorLogEntity.class, params);
                for (CbsEquipmentErrorLogEntity cbsEquipmentErrorLog : listCbsEquipmentErrorLogEntitys) {
                    cbsEquipmentErrorLogService.save(cbsEquipmentErrorLog);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }


}
